package com.daokin.controller;

import com.daokin.constant.SystemConstant;
import com.daokin.dto.User;
import com.daokin.service.UserService;
import com.daokin.util.HttpUtils;
import com.daokin.util.JSONPUtil;
import com.daokin.vo.JsonVo;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class LoginController {

    private static final Logger LOGGER = Logger.getLogger(LoginController.class);
    @Autowired
    private UserService userService;

    @RequestMapping("/login.htm")
    public String login(Map<String, Object> model) {
        return "login";
    }

    @RequestMapping(value = "/logout.htm", method = RequestMethod.GET)
    public String userLogout(HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession().getAttribute(
                SystemConstant.SESSION_USER_KEY);
        if (user != null) {
            LOGGER.info("Web logout! for the user: " + user.getUser());
            request.getSession().removeAttribute(SystemConstant.SESSION_USER_KEY);
        }
        return "redirect:" + HttpUtils.getBasePath(request) + "/login.htm";
    }

    @ResponseBody
    @RequestMapping(value = "/login.json", method = RequestMethod.POST)
    public JsonVo<String> userLogin(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "password") String password,
            HttpServletRequest request, ModelMap modelMap) {
        LOGGER.info("Web login...");
        JsonVo<String> json = new JsonVo<String>();
        try {

            User user = userService.getUserByName(name);
            if (user == null) {
                json.setResult(false);
                json.getErrors().put("fail_msg", "User does not exist.");
                return json;
            }
            userService.userLogin(user, password, request);
            LOGGER.info("Login success! for the user: " + name);
            json.setResult(true);
        } catch (Exception e) {
            json.setResult(false);
            if (json.getErrors().get("fail_msg") == null) {
                json.getErrors().put("fail_msg", "Email or password incorrect.");
            }
            json.setMsg(e.getLocalizedMessage());
            LOGGER.error("Web login failed!" + e);
            e.printStackTrace();
        }
        return json;
    }
}
